/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JOrderAnalysisDialog.java
 *
 * Created on 2009-11-25, 9:15:16
 */

package cn.ekuma.epos.qkorder.dialog;

import cn.ekuma.epos.bean.util.erp.OrderHelper;
import cn.ekuma.epos.businesslogic.OrderUtil;
import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.order.JOrderLines;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValEntry;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.LocalRes;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.bean.Customer;
import com.openbravo.bean.Location;
import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.OrderLine;
import com.openbravo.bean.erp.OrderState;
import com.openbravo.bean.erp.OrderType;
import com.openbravo.bean.infobean.CustomerInfo;
import com.openbravo.pos.scripting.ScriptEngine;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.scripting.ScriptFactory;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

/**
 *
 * @author Administrator
 */
public class JOrderAnalysisDialog extends javax.swing.JDialog {
   
	 private static Logger logger = Logger.getLogger("cn.ekuma.epos.qkorder.dialog.JOrderAnalysisDialog");
	
	public static String RESOURCE="OrderAnalysis";
	
    protected I_DataLogicSystem dlSystem;
    private AppView m_App;
    private JOrderLines m_Orderlines;
    private Order order;
	private I_DataLogicReceipts dlReceipts;
	private I_DataLogicCustomers dlCustomers;
	private I_DataLogicERP dlSales;
	private HashMap<String,String> analysisMap;
	

    private static String Dull_less="if(orderline.getConsulMultiply()>orderline.getMultiply()){"+"\r\n"+
                                           "orderline.setFilter(false);"+"\r\n"+
                                     "};";

    private static String Dull_great="if(orderline.getConsulMultiply()<orderline.getMultiply()){"+"\r\n"+
                                           "orderline.setFilter(false);"+"\r\n"+
                                     "};";

    private static String Dull_ConsulZero="if(orderline.getConsulMultiply()==0){"+"\r\n"+
                                           "orderline.setFilter(false);"+"\r\n"+
                                     "};";

    private static String Dull_UnitZero="if(orderline.getMultiply()==0){"+"\r\n"+
                                           "orderline.setFilter(false);"+"\r\n"+
                                     "};";

    private static String[] TEMPCodes=new String[]{"Dull_less","Dull_great","Dull_ConsulZero","Dull_UnitZero"};

    private static Map<String,String> TEMPCODEMAP=new HashMap();
    {
        TEMPCODEMAP.put("Dull_less", Dull_less);
        TEMPCODEMAP.put("Dull_great", Dull_great);
        TEMPCODEMAP.put("Dull_ConsulZero", Dull_ConsulZero);
        TEMPCODEMAP.put("Dull_UnitZero", Dull_UnitZero);
    }



    /** Creates new form JOrderAnalysisDialog 
     * @wbp.parser.constructor*/
    public JOrderAnalysisDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);  
        initComponents();
    }

     private JOrderAnalysisDialog(Dialog dialog, boolean b) {
        super(dialog, b);
        initComponents();
    }

      public static JOrderAnalysisDialog newJDialog(Component comp,AppView m_App,Order order,I_DataLogicERP dlSales,I_DataLogicCustomers dlCustomers,I_DataLogicReceipts dlReceipts,I_DataLogicSystem dlSystem){
        Window window = getWindow(comp);
        JOrderAnalysisDialog mydialog;
        if (window instanceof Frame) {
            mydialog = new JOrderAnalysisDialog((Frame) window, true);
        } else {
            mydialog = new JOrderAnalysisDialog((Dialog) window, true);
        }
        mydialog.init(m_App,order, dlSales, dlCustomers, dlReceipts, dlSystem);
        return mydialog;
    }

    private static Window getWindow(Component parent) {
        if (parent == null) {
            return new JFrame();
        } else if (parent instanceof Frame || parent instanceof Dialog) {
            return (Window) parent;
        } else {
            return getWindow(parent.getParent());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jSplitPane1.setPreferredSize(new Dimension(121, 50));
        jSplitPane1.setOneTouchExpandable(true);
        jPanel1 = new javax.swing.JPanel();
        jPanel1.setPreferredSize(new Dimension(10, 80));
        jPanel2 = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        m_jPanelCentral = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jState = new javax.swing.JEditorPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setLayout(new java.awt.BorderLayout());
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1.add(jScrollPane1, BorderLayout.CENTER);
        jCode = new javax.swing.JEditorPane();
        
                jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                jScrollPane1.setViewportView(jCode);

        jSplitPane1.setTopComponent(jPanel1);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jSplitPane2.setDividerLocation(500);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        m_jPanelCentral.setLayout(new java.awt.BorderLayout());
        jSplitPane2.setTopComponent(m_jPanelCentral);

        jState.setEditable(false);
        jScrollPane2.setViewportView(jState);

        jSplitPane2.setRightComponent(jScrollPane2);

        jPanel2.add(jSplitPane2, java.awt.BorderLayout.CENTER);

        jSplitPane1.setRightComponent(jPanel2);

        getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-603)/2, (screenSize.height-588)/2, 791, 596);
    	
    	panel = new JPanel();
    	getContentPane().add(panel, BorderLayout.EAST);
    	panel.setLayout(new BorderLayout(0, 0));
    	jPanel3 = new javax.swing.JPanel();
    	panel.add(jPanel3, BorderLayout.NORTH);
    	jButton1 = new javax.swing.JButton();
    	jButton2 = new javax.swing.JButton();
    	jTempCode = new javax.swing.JComboBox();
    	
    	        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
    	        jButton1.setText(AppLocal.getIntString("label.run")); // NOI18N
    	        jButton1.addActionListener(new java.awt.event.ActionListener() {
    	            public void actionPerformed(java.awt.event.ActionEvent evt) {
    	                jButton1ActionPerformed(evt);
    	            }
    	        });
    	        
    	                jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
    	                jButton2.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N
    	                jButton2.addActionListener(new java.awt.event.ActionListener() {
    	                    public void actionPerformed(java.awt.event.ActionEvent evt) {
    	                        jButton2ActionPerformed(evt);
    	                    }
    	                });
    	                
    	                        jTempCode.addItemListener(new java.awt.event.ItemListener() {
    	                            public void itemStateChanged(java.awt.event.ItemEvent evt) {
    	                                jTempCodeItemStateChanged(evt);
    	                            }
    	                        });
    	                                
    	                                JButton btnNewButton = new JButton(AppLocal.getIntString("button.print"));
    	                                btnNewButton.addActionListener(new ActionListener() {
    	                                	public void actionPerformed(ActionEvent e) {
    	                                		printTable();
    	                                	}
    	                                });
    	                                btnNewButton.setIcon(new ImageIcon(JOrderAnalysisDialog.class.getResource("/com/openbravo/images/fileprint.png")));
    	                                
    	                                JButton btnNewButton_1 = new JButton(AppLocal.getIntString("button.createOrder"));
    	                                btnNewButton_1.addActionListener(new ActionListener() {
    	                                	public void actionPerformed(ActionEvent e) {
    	                                		createNewOrder();
    	                                	}
    	                                });
    	                                btnNewButton_1.setIcon(new ImageIcon(JOrderAnalysisDialog.class.getResource("/com/openbravo/images/editnew.png")));
    	                        
    	                                javax.swing.GroupLayout gl_jPanel3 = new javax.swing.GroupLayout(jPanel3);
    	                                gl_jPanel3.setHorizontalGroup(
    	                                	gl_jPanel3.createParallelGroup(Alignment.LEADING)
    	                                		.addGroup(gl_jPanel3.createSequentialGroup()
    	                                			.addContainerGap()
    	                                			.addGroup(gl_jPanel3.createParallelGroup(Alignment.LEADING)
    	                                				.addComponent(jButton1, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
    	                                				.addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
    	                                				.addComponent(jTempCode, Alignment.TRAILING, 0, 95, Short.MAX_VALUE)
    	                                				.addComponent(btnNewButton)
    	                                				.addComponent(btnNewButton_1))
    	                                			.addContainerGap())
    	                                );
    	                                gl_jPanel3.setVerticalGroup(
    	                                	gl_jPanel3.createParallelGroup(Alignment.LEADING)
    	                                		.addGroup(gl_jPanel3.createSequentialGroup()
    	                                			.addGap(23)
    	                                			.addComponent(jButton1)
    	                                			.addPreferredGap(ComponentPlacement.RELATED)
    	                                			.addComponent(jButton2)
    	                                			.addPreferredGap(ComponentPlacement.RELATED)
    	                                			.addComponent(btnNewButton)
    	                                			.addPreferredGap(ComponentPlacement.RELATED)
    	                                			.addComponent(btnNewButton_1)
    	                                			.addPreferredGap(ComponentPlacement.RELATED)
    	                                			.addComponent(jTempCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
    	                                			.addContainerGap(11, Short.MAX_VALUE))
    	                                );
    	                                gl_jPanel3.linkSize(SwingConstants.HORIZONTAL, new Component[] {jButton1, jButton2, btnNewButton, btnNewButton_1});
    	                                jPanel3.setLayout(gl_jPanel3);
    	                                
    	                                list = new JList();
    	                                list.addListSelectionListener(new ListSelectionListener() {
    	                                	public void valueChanged(ListSelectionEvent e) {
    	                                		String selectTemp=(String) list.getSelectedValue();
    	                                        jCode.setText(analysisMap.get(selectTemp));
    	                                	}
    	                                });
    	                                panel.add(list, BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    protected void createNewOrder() {
		if(m_Orderlines.getOrderLines()==null||m_Orderlines.getOrderLines().isEmpty())
			return;
		Order newOrder=newOrder();
		if(newOrder!=null){
			try {
				OrderUtil.addOrderLineForAllReadyList(dlSales, newOrder, m_Orderlines.getOrderLines());
				dlReceipts.insertSharedOrderNoLock(newOrder.getId(),newOrder);
			} catch (BasicException e) {
				 MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                 msg.show(this);
                 return;
			}
			MessageInf msg = new MessageInf(MessageInf.SGN_SUCCESS, AppLocal.getIntString("message.createOrderCompleted"));
            msg.show(this);
		}
	}

	protected void printTable() {
    	m_Orderlines.printTable();
	}

	private void jTempCodeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jTempCodeItemStateChanged
        String selectTemp=(String) ((ComboBoxValEntry)evt.getItem()).getKey();
        jCode.setText(TEMPCODEMAP.get(selectTemp));
    }//GEN-LAST:event_jTempCodeItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if (jCode.getText() == null) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotexecute"));
                msg.show(this);
                return;
            }
           ScriptEngine  script = ScriptFactory.getScriptEngine(ScriptFactory.BEANSHELL);
            jState.setText(null);
            m_Orderlines.clearOrderLines();
            for (OrderLine l : order.getLines()) {
                l.setFilter(true);
                try {
                    evalScript(script,l);
                } catch (ScriptException ex) {
                    jState.setText(ex.getMessage());
                    break;
                }  
                if (!l.isFilter()) {
                    m_Orderlines.addOrderLine(l);
                }
            }
        } catch (ScriptException ex) {
            new MessageInf(ex).show(this);
            jState.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void  init(AppView m_App,Order order,I_DataLogicERP dlSales,I_DataLogicCustomers dlCustomers,I_DataLogicReceipts dlReceipts,I_DataLogicSystem dlSystem){
        this.order=order;
        this.m_App=m_App;
        this.dlSystem =dlSystem;
        this.dlReceipts =dlReceipts;
        this.dlCustomers = dlCustomers;
        this.dlSales =dlSales;
        m_Orderlines = new JOrderLines(dlSystem.getResourceAsXML("Order.Line"));
        m_jPanelCentral.add(m_Orderlines, java.awt.BorderLayout.CENTER);
        jCode.setText(null);
        for(String codeName:TEMPCodes)
          jTempCode.addItem(buildEntry(codeName));
        init(dlSystem.getResourceAsXML(RESOURCE));
        if(analysisMap!=null)
        	list.setListData(analysisMap.keySet().toArray());
    }
    
    private static SAXParser m_sp = null;
    
    public void init(String resource){
       if (resource != null) {
           try {
               if (m_sp == null) {
                   SAXParserFactory spf = SAXParserFactory.newInstance();
                   m_sp = spf.newSAXParser();
               }
               ColumnsHandler columnshandler = new ColumnsHandler();
               m_sp.parse(new InputSource(new StringReader(resource)), columnshandler);
               analysisMap = columnshandler.getAnalysisMap();

           } catch (ParserConfigurationException ePC) {
               logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
           } catch (SAXException eSAX) {
               logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
           } catch (IOException eIO) {
               logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
           }
       }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JEditorPane jCode;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JEditorPane jState;
    private javax.swing.JComboBox jTempCode;
    private javax.swing.JPanel m_jPanelCentral;
    private JPanel panel;
    private JList list;
    // End of variables declaration//GEN-END:variables

    public void evalScript(ScriptEngine  script,OrderLine line) throws ScriptException {
         script.put("orderline", line);
         script.eval(jCode.getText());
    }

    private ComboBoxValEntry buildEntry(String prop){
        String localkey="list.orderanalysis."+prop;
        ComboBoxValEntry entry=new ComboBoxValEntry(prop,AppLocal.getIntString(localkey));
        return entry;
    }
   
    
    public Order newOrder() {
        JOrderTypeDialog orderTypeDialog=JOrderTypeDialog.getDialog(this);
        try {
            orderTypeDialog.init(m_App, null, dlSales, dlCustomers);
            orderTypeDialog.setVisible(true);
        } catch (BasicException ex) {
             MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotSetupOrderType"), ex);
             msg.show(this);
        }
        if(orderTypeDialog.isOk()){
            Order order = new Order();
            order.setDate(orderTypeDialog.getCreateDate());
            order.setID(UUID.randomUUID().toString());
            order.setOrderId(OrderHelper.generateOrderId());
            order.setDefineType(orderTypeDialog.getoType());
            order.setOrderType(orderTypeDialog.getOrderType());
            order.setUser(m_App.getAppUserView().getUser().getUserInfo());
            CustomerInfo customerInfo=orderTypeDialog.getCustomerInfo();
            if(order.getDefineType().isProductConsult()){
                order.setConsultProductId(orderTypeDialog.getProdcutID());
                order.setConsultProductAttsetinstid(orderTypeDialog.getProductInstDescID());
                order.setConsultProductName(orderTypeDialog.getProdcutName());
            }
            try {
            order.setCustomer((Customer) (customerInfo == null ? null : dlSales.findByStringId(Customer.class, customerInfo.getId())));
             } catch (BasicException e) {
               MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindcustomer"), e);
               msg.show(this);
            }
            Location location=orderTypeDialog.getoLocateion();
            if(location!=null){
                 order.setLocationRef(location.getID());
                 order.setLocationDesc(location.printName());
                 order.setDeliverType(orderTypeDialog.getDeliverType());
                 order.setDeliverTypeDesc(orderTypeDialog.getDeliverTypeDesc());
            }
            location=orderTypeDialog.getoLocateion1();
            if(location!=null){
                 order.setLocationRef1(location.getID());
                 order.setLocationDesc1(location.printName());
            }
            if(order.getDefineType().getConsultType()==OrderType.CONSULTTYPE_Order||order.getDefineType().getConsultType()==OrderType.CONSULTTYPE_TimeSliceStore)
                 order.setConsultRef(orderTypeDialog.getConsultID());
            order.setReference_User(orderTypeDialog.getReferencePerson());
            order.addState(new OrderState(m_App.getAppUserView().getUser().getUserInfo(),AppLocal.getIntString(OrderState.ORDERSTATE_Start)));
            
            return order;
          }
        return null;
    }
    
private static class ColumnsHandler extends DefaultHandler {
        private String dispname;
        private HashMap<String,String> analysisMap;
        private StringBuffer buf;

        @Override
        public void startDocument() throws SAXException {
        	analysisMap=new HashMap<String,String>();
        }
        @Override
        public void endDocument() throws SAXException {}    
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
        	dispname=null;
        	
        	if ("key".equals(qName)){
                dispname = attributes.getValue("display");
                buf=new StringBuffer();
            }
        }      
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
        	if ("key".equals(qName))
        		analysisMap.put(dispname, buf.toString());
        }
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
        	
        	if(dispname!=null)
        		buf.append(ch, start, length);
        }
		public HashMap<String, String> getAnalysisMap() {
			return analysisMap;
		}
    }
}
